import { useMemoizedFn } from 'ahooks';
import { Button } from 'antd';
import { isNil } from 'lodash';
import { useCesium } from 'resium';

const dataURLtoBlob = (dataurl: string) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/);
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime ? mime[1] : 'image/octet-stream',
    });
};

export default function Screenshot() {
    const { viewer } = useCesium();

    const onClick = useMemoizedFn(() => {
        if (isNil(viewer)) return;
        viewer.render();
        const canvas = viewer.scene.canvas;
        const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
        const link = document.createElement('a');
        const blob = dataURLtoBlob(image);
        const objurl = URL.createObjectURL(blob);
        link.download = 'scene.png';
        link.href = objurl;
        link.click();
    });

    return (
        <>
            <div
                style={{
                    position: 'absolute',
                    left: '10px',
                    top: '10px',
                }}
            >
                <Button type="primary" onClick={onClick}>
                    截图
                </Button>
            </div>
        </>
    );
}
